package com.hll.api.service.impl;

import com.hll.api.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Objects;
import java.util.Random;

/**
 * @author Administrator
 * @create 2019-06-23 19:19
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {
    final
    JavaMailSenderImpl mailSender;
    private static final String allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Autowired
    public MailServiceImpl(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }


    @Override
    public String send(String mail) {
        String code =generateString();

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper( mimeMessage, true );
            //标题
            mimeMessageHelper.setSubject( "欢迎注册为网易考拉用户");
            //内容
            mimeMessageHelper.setText( "您的验证码为：<h5 style=\"color: orangered\">"+code+"</h5><br/>验证码有效时间为30分钟！",true);
            //发件人
            mimeMessageHelper.setFrom( Objects.requireNonNull( mailSender.getUsername() ) );
            //收件人
            mimeMessageHelper.setTo(mail);
            //发送
            mailSender.send(mimeMessage);
            log.debug("验证码发送成功=》邮箱：{}，验证码：{}",mail,code);

        }catch (Exception e){
            System.out.println("发送失败，错误信息:");
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 由大小写字母、数字组成的随机字符串
     */
    private static String generateString() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }
}
